package com.wzh.live.mq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.wzh.common.utils.R;
import com.wzh.live.dao.LiveGoodsDao;
import com.wzh.live.dao.OrderLiveDao;
import com.wzh.live.entity.GoodsEntity;
import com.wzh.live.entity.LiveGoodsEntity;
import com.wzh.live.entity.OrderLiveEntity;
import com.wzh.live.feign.GoodsFeign;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

/**
 * @author WZH
 * @title: Comsumer
 * @projectName miaosha
 * @description:
 * @date 2022/3/15
 */
@Component
public class Consumer {

    @Autowired
    private LiveGoodsDao liveGoodsDao;

    @Autowired
    private OrderLiveDao orderLiveDao;

    @Autowired
    private GoodsFeign goodsFeign;



    @RabbitListener(queues = "msg4")
    public void take(OrderLiveEntity orderLive, Message message, Channel channel) throws IOException {
        R goodsInfo = goodsFeign.info(orderLive.getGoodsId());
        if (goodsInfo.getCode()==0) {
            String goodsJsonString = JSON.toJSONString(goodsInfo.get("goods"));
            GoodsEntity goods = JSON.parseObject(goodsJsonString, GoodsEntity.class);
            LiveGoodsEntity liveGoods=liveGoodsDao.getByLiveIdAndGoodsId(orderLive.getActivityId(),orderLive.getGoodsId());
            orderLive.setGoodsName(goods.getGoodsName());
            orderLive.setGoodsPrice(liveGoods.getPrice().multiply(new BigDecimal(orderLive.getGoodsCount())));
            orderLive.setGoodsChannel(1);
            orderLive.setStatus(0);
            String orderNo = UUID.randomUUID().toString().replace("-", "");
            orderLive.setOrderNo(orderNo);
            orderLive.setCreateDate(new Date());
            orderLiveDao.insert(orderLive);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
